package com.woniuxy.user.controller;

import com.woniuxy.entity.Role;
import com.woniuxy.entity.User;
import com.woniuxy.user.service.RoleService;
import com.woniuxy.user.service.UserService;
import com.woniuxy.utils.JWTUtil;
import com.woniuxy.utils.MD5;
import com.woniuxy.utils.ResponseResult;
import com.woniuxy.utils.ResultStatus;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    RoleService roleService;

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 登录认证
     * @param user
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResponseResult auth(@RequestBody User user, HttpServletResponse response, HttpSession session) {
        //1.逻辑:通过账号查找账号信息，然后比对密码（密码加密）  引入MD5加密工具
        User dbuser = userService.getUserByName(user.getUsername());
//        String pwd = user.getPassword();
        String pwd = MD5.getMd5(user.getPassword());
        if (dbuser==null){
            return new ResponseResult(500, ResultStatus.LOGIN_FAILED, "账号不存在", null);
        }
        if (!dbuser.getPassword().equals(pwd)){
            return new ResponseResult(500, ResultStatus.LOGIN_FAILED, "密码错误", null);
        }
        //假设验证成功
        session.setAttribute("user", dbuser);
        System.out.println("----------------------------"+session.getAttribute("user"));
        //1.生成token、refreshToken
        String token = JWTUtil.generateToken(user.getUsername());
        String refreshToken = UUID.randomUUID().toString();

        //2.将token、refreshToken放到Redis中
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("uname", user.getUsername());
        //以refreshToken作为key，map作为value存放到redis中
        redisTemplate.opsForHash().putAll(refreshToken, map);
        //设置refreshToken的过期时间
        redisTemplate.expire(refreshToken, JWTUtil.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);
        //3.将token、refreshToken放到响应头中返回给浏览器
        response.setHeader("authentication", token);
        response.setHeader("refresh", refreshToken);
        //4.向前端暴露自定义的响应头
        response.setHeader("Access-Control-Expose-Headers", "authentication,refresh,user");
        //登录成功，将user响应给前端
        ResponseResult result = new ResponseResult(200, ResultStatus.LOGIN_SUCCESS, "登陆成功", dbuser);
        return result;
    }

    //鉴权方法
    @GetMapping("/hasPerms/{account}/{perms}")
    public ResponseResult hasPerms(@PathVariable("account") String account, @PathVariable("perms") String perms) {
        System.out.println("鉴权");
        //通过账号查询到所有的权限信息    5张表
        List<String> permsList = new ArrayList<>();
        userService.getUserByName(account).getRole().getPermissions().forEach(p->permsList.add(p.getPermname()));
        boolean result = permsList.contains(perms);
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        if (result) {
            responseResult.setStatus(ResultStatus.HAVE_PERMS);
        }else {
            responseResult.setStatus(ResultStatus.NO_PERMS);
        }
        return responseResult;
    }

    @GetMapping("/test")
    public String test(){
        return "跨域连接正常";
    }

    /**
     * 查询所有用户
     * @return
     */
//    @RequirePerms("user:all")
    @GetMapping("/all")
    public List<User> all(){
       return userService.getAllUsers();
    }

    /**
     * 通过id查询用户
     * @param id
     * @return
     */
    @GetMapping("/get")
    public User getUser(int id){
        return userService.getUser(id);
    }

    /**
     * 通过名字查询用户
     * @param username
     * @return
     */
    @GetMapping("/getusername")
    public User getUser(String username){
        return userService.selectOneUserByName(username);
    }

    /**
     * 通过用户名查询用户
     * @param username
     * @return
     */
    @GetMapping("/queryByname")
    public ResponseResult queryByname(String username){
        try {
            List<User> users = userService.getName(username);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "请求成功", users);
        } catch (Exception e){
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "请求失败", null);
        }
    }

    /**
     * 通过证件号查询用户
     * @param idcard
     * @return
     */
    @GetMapping("/queryByidcard")
    public ResponseResult queryByidcard(String idcard){
        try {
            List<User> users = userService.getIdcard(idcard);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "请求成功", users);
        } catch (Exception e){
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "请求失败", null);
        }
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PutMapping("/add")
    public ResponseResult addUser(@RequestBody User user){
        try {
            user.setPassword(MD5.getMd5("123"));
            Role role = roleService.getRoleByName(user.getRole().getRolename()).get(0);
            user.setRole(role);
            System.out.println(user);
            userService.addUser(user);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "添加成功", null);
        } catch (Exception e) {
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "添加失败", null);
        }
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping("/update")
    public ResponseResult updateUser(@RequestBody User user){
        try {
            System.out.println(user);
            Role role = roleService.getRoleByName(user.getRole().getRolename()).get(0);
            user.setRole(role);
            userService.updateUser(user);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "修改失败", null);
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public ResponseResult delUser(@PathVariable("id") int id){
        try {
            userService.deleteUser(id);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "删除成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "删除失败", null);
        }
    }

    @PutMapping("/changePwd")
    public ResponseResult changePwd(@RequestBody User user){
        try {
            System.out.println(user);
            user.setPassword(MD5.getMd5(user.getPassword()));
            userService.changePwd(user);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "密码修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "密码修改失败", null);
        }
    }
}
